package com.dsg.controller.apply;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dsg.common.constants.MessageConstants;
import com.dsg.common.dto.AjaxResult;
import com.dsg.common.util.toolbox.StringUtil;
import com.dsg.controller.base.BaseController;
import com.dsg.entity.apply.DsgApplyEncl;
import com.dsg.entity.dto.CusEnclDto;
import com.dsg.entity.system.DsgSysFile;
import com.dsg.service.apply.IDsgApplyEnclService;
import com.dsg.service.system.IDsgSysFileService;
import com.dsg.util.FileUtil;
import io.swagger.annotations.*;
import org.apache.xerces.impl.dv.util.Base64;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;

/**
 * <p>
 * 申请单附件资料 前端控制器
 * </p>
 *
 * @author system
 * @since 2020-07-10
 */
@RestController
@RequestMapping("/apply/dsgApplyEncl")
@Api(description = "申请单附件资料")
public class DsgApplyEnclController extends BaseController {

    @Autowired
    private IDsgApplyEnclService enclService;
    @Autowired
    private IDsgSysFileService fileService;

    @GetMapping(value = "/selectCusEncl")
    @ApiOperation("客戶資料-附件")
    @ApiResponses(
            @ApiResponse(response = CusEnclDto.class, code = 0, message = "ok")
    )
    public AjaxResult selectCusEncl(String cusNo, String createTimeBegin, String createTimeEnd, String carNo, String appNo) {
        List<CusEnclDto> list = fileService.selectCusEncl(cusNo, createTimeBegin, createTimeEnd, carNo, appNo, getEntCode());
        return success(list);
    }

    @GetMapping(value = "/listByRelId")
    @ApiOperation("查询關聯relId的附件")
    public AjaxResult listByRelId(String relId) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("REL_ID", relId);
        List<DsgSysFile> list = fileService.list(wrapper);
        return success(list);
    }

    @GetMapping(value = "/listByType")
    @ApiOperation("查询特定類型的附件")
    public AjaxResult listByType(String appNo, String enclTypes) {
        List<DsgSysFile> list = fileService.listByType(appNo, enclTypes);
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, list);
        return ajaxResult;
    }

    @GetMapping(value = "/listByBill")
    @ApiOperation("查询申请单对应的附件")
    public AjaxResult listByBill(@ApiParam(value = "申请单号", required = true) String appNo) {
        List<DsgSysFile> list = fileService.listByBill(appNo);
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, list);
        return ajaxResult;
    }

    @GetMapping(value = "/export")
    @ApiOperation("下載附件")
    public void export(@NotNull HttpServletResponse response, String oid) throws Exception {
        DsgSysFile file = fileService.getById(oid);
        ServletOutputStream out = response.getOutputStream();
        try {
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Length", "" + (file.getFileContent().length-10));
            response.setHeader("Content-disposition", "attachment; filename=" + "attachment." + file.getFileType());
            out.write(file.getFileContent());
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

    @GetMapping(value = "/list")
    @ApiOperation("查询列表")
    public AjaxResult list(DsgApplyEncl applyEncl) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("APP_NO", applyEncl.getAppNo());
        List<DsgApplyEncl> list = enclService.list(wrapper);
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, list);
        return ajaxResult;
    }

    @GetMapping(value = "/view")
    @ApiOperation("查询一个附件")
    public AjaxResult get(DsgApplyEncl applyEncl) {
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("ENCL_TYPE", applyEncl.getEnclType());
        wrapper.eq("REL_ID", applyEncl.getRelId());
        DsgApplyEncl encl = enclService.getOne(wrapper);
        AjaxResult ajaxResult = json(MessageConstants.SSO_STATUS_SUCCESS, encl);
        return ajaxResult;
    }

    /**
     * 查询单条数据
     *
     * @param id
     * @return
     */
    @GetMapping(value = "/{id}/view")
    @ApiOperation("查询单条数据")
    public AjaxResult view(@PathVariable String id) {
        DsgSysFile file = fileService.getById(id);
        String fileType = file.getFileType();
        if (fileService.isImage(fileType)) {
            String base64Str = Base64.encode(file.getFileContent());
            file.setBase64(base64Str);
        }
        return json(MessageConstants.SSO_STATUS_SUCCESS, file);
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping(value = "/add")
    @ApiOperation("新增")
    public AjaxResult add(DsgSysFile dsgSysFile, @ApiParam(value = "file", name = "file", required = true) @RequestParam("file") MultipartFile file) throws Exception {
        if (StringUtil.isEmpty(dsgSysFile.getRelId())) {
            throw new Exception("relId不能為空");
        }

        String fileName = file.getOriginalFilename();
        String[] fileNameArr = fileName.split("\\.");
        String fileType = "png";
        if (fileNameArr.length > 1) {
            fileType = fileNameArr[1];
        }

        File f = FileUtil.multipartToFile(file);
        fileService.saveFile(dsgSysFile, f, dsgSysFile.getRelId(), fileType);
        return result(MessageConstants.SSO_STATUS_SUCCESS);
    }

    /**
     * 更新
     *
     * @param applyEncl
     * @return
     */
    @PutMapping(value = "/update")
    @ApiOperation("更新")
    public AjaxResult update(@RequestBody DsgApplyEncl applyEncl) {
        enclService.updateById(applyEncl);
        return json(MessageConstants.SSO_STATUS_SUCCESS, applyEncl);
    }

    @Transactional(rollbackFor = Exception.class)
    @DeleteMapping(value = "/{id}/delete")
    @ApiOperation("删除附件")
    public AjaxResult deleteOne(@PathVariable String id) {
        fileService.removeById(id);
        return result(MessageConstants.SSO_STATUS_SUCCESS);
    }
}
